﻿using System.Collections;
using System.Reflection;

namespace QuickORM.BLL
{
    public class Reflect<T> where T : class
    {
        private static readonly Hashtable ObjCache = new Hashtable();
        private static readonly object syncRoot = new object();

        public static T Create(string sName, string sFilePath)
        {
            return Create(sName, sFilePath, true);
        }

        public static T Create(string sName, string sFilePath, bool bCache)
        {
            var CacheKey = sName;
            T objType = null;
            if (bCache)
            {
                objType = (T) ObjCache[CacheKey]; //从缓存读取 
                if (!ObjCache.ContainsKey(CacheKey))
                {
                    lock (syncRoot)
                    {
                        var assObj = CreateAssembly(sFilePath);
                        var obj = assObj.CreateInstance(CacheKey);
                        objType = (T) obj;

                        ObjCache.Add(CacheKey, objType); //缓存数据访问对象
                    }
                }
            }
            else
            {
                objType = (T) CreateAssembly(sFilePath).CreateInstance(CacheKey); //反射创建 
            }

            return objType;
        }

        public static Assembly CreateAssembly(string sFilePath)
        {
            var assObj = (Assembly) ObjCache[sFilePath];
            if (assObj == null)
            {
                assObj = Assembly.Load(sFilePath);
                ObjCache.Add(sFilePath, assObj); //将整个程序集对象装入缓存
            }
            return assObj;
        }
    }
}